#include "cnlistwidget.h"
#include <QMouseEvent>
#include <QApplication>
#include <QDrag>
#include <QMimeData>
#include <QPixmap>

CNListWidget::CNListWidget(QWidget *parent):
    QListWidget(parent)
{
    setViewMode(QListView::IconMode);
    setAcceptDrops(false);
    setIconSize(QSize(54, 54));
}

void CNListWidget::mousePressEvent(QMouseEvent *event)
{
    m_pressedPoint = event->pos();
    QListWidget::mousePressEvent(event);
}

void CNListWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons().testFlag(Qt::LeftButton)) {
        QPoint pos = event->pos();
        QListWidgetItem* currentItem = itemAt(m_pressedPoint);

        if (currentItem && (pos - m_pressedPoint).manhattanLength() >= QApplication::startDragDistance()) {
            QDrag* drag = new QDrag(this);
            QString icon = currentItem->data(Qt::UserRole + 1).toString();

            QMimeData* mimeData = new QMimeData;
            mimeData->setText(currentItem->data(Qt::UserRole).toString());
            mimeData->setData(currentItem->data(Qt::UserRole).toString(), QByteArray());
            drag->setMimeData(mimeData);

            drag->setPixmap(QPixmap(icon));
            drag->setHotSpot(QPoint(20, 20));

            drag->exec(Qt::CopyAction);
        }
    }
}
